#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月31日

@author: chenyongbing
'''
import sys,os,commands
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson 
from django.utils.http import urlquote
from django.contrib.auth.decorators import login_required  
from django.views.decorators.csrf import csrf_exempt
from django.core.servers.basehttp import FileWrapper
from django.shortcuts import render
from forms import *
import re,os,datetime


from export_macs import myExportMacs
sys.path.append(os.path.join(current_dir,'../../'))
from base.form_datas import FormDatas
myFormDatas = FormDatas()
from base.retail_datas import myRetailDatas
import logging



from localConfig import LocalConfig


def export_base_feild_form(request,myForm,initial):
    #myForm.initial= initial
    if initial.has_key('province'):
        prov = initial['province']
    else:
        prov = None
    if initial.has_key('city'):
        city = initial['city']
    else:
        city = None
    
    if initial.has_key('dist'):
        dist = initial['dist']
    else:
        dist = None
    
    if initial.has_key('cate'):
        cate = initial['cate']
    else:
        cate = None
        
    if initial.has_key('company'):
        comp_id = initial['company']
    else:
        comp_id = None
    if initial.has_key('group'):
        group = initial['group']
    else:
        group = None
    
    if prov=='province':prov = None
    if cate == 'cate':cate= None
    if comp_id=='company':comp_id=None
    if city == 'city':city = None
    if dist == 'dist':dist=None
    if group == 'group':group = None
    #[['company','请选择公司']]+
    companies = myFormDatas.get_companies_data(cate=cate, prov=prov, city=city, 
 dist=None)
    
    #groups = [['group','请选择门店']] 
    if comp_id!=None or prov!=None:
        groups =   myFormDatas.get_groups_data(comp_id=comp_id, prov=prov, city=city, dist=dist)
    else:
        groups = []
    #[['cate','请选择类别']]+
    cates = myFormDatas.get_cates_data(prov=prov, city=city, dist=dist,comp_id=comp_id)
    #[['province','请选择省份']]+
    provinces =  myFormDatas.get_region_data(cate=cate, comp_id=comp_id)
    
    cities = [['city','请选择城市']]
    if prov!=None and prov!='province':
         cities =  myFormDatas.get_region_data(cate=cate, comp_id=comp_id, prov=prov)
    else:
        cities = []
    #dists = [['dist','请选择区域']]
    if city!=None and city!='city':
        dists =  myFormDatas.get_region_data(cate=cate, comp_id=comp_id, prov=prov, city=city)
    else:
        dists = []
    #myForm.initial({'company':companies,'cates':cates,'province':provinces})
    myForm.fields['company'].choices +=companies
    myForm.fields['cate'].choices +=cates
    myForm.fields['province'].choices +=provinces
    myForm.fields['city'].choices +=cities
    myForm.fields['dist'].choices +=dists
    myForm.fields['group'].choices +=groups
    return myForm
    


def __export_file__name__(export_path='',prefix='',suffix='',comp_id=None,cate=None,prov=None,city=None,dist=None,startTime=None,group=None,endTime=None,otype=None,mtype=None):
    def estr_len(estr):
        if len(estr)==0:return 0
        else:
            return 1
        
    export_file = prefix
    if cate!=None:
        export_file=export_file+'_'+cate
    if comp_id!=None:
        company_name = myRetailDatas.get_comp_name(comp_id= comp_id)
        export_file=export_file+'_'+company_name
        logging.debug('%s type %s'%(company_name,type(company_name)))
    if group!=None:
        group_name = myRetailDatas.get_group_name(group=group)
        logging.debug('%s type %s'%(group_name,type(group_name)))
        export_file=export_file+'_'+group_name
    if prov!=None:
        export_file=export_file+'_'+prov
    if city!=None:
        export_file=export_file+'_'+city
    if dist!=None:
        export_file=export_file+'_'+dist
    if otype!=None:
        export_file=export_file+'_'+otype
    if mtype!=None:
        export_file=export_file+'_'+mtype
      
    logging.debug('%s type %s'%(export_path,type(export_path)))
    if startTime ==endTime:
        export_file=export_file+'(%s)'%(re.sub('-','.',startTime))
    else:
        export_file=export_file+'(%s-%s)'%(re.sub('-','.',startTime),re.sub('-','.',endTime))
    if len(suffix)!=0:
        export_file+='.%s'%suffix
   
    logging.debug('%s type %s'%(export_file,type(export_file)))
    return export_file





def export_macs_from_mysql(request):
    '''mac地址导出'''
    #print request
    day = datetime.date.today().strftime('%Y-%m-%d')
    export_path = os.path.join(current_dir,'../../templates/download/macs/%s'%day) 
    if request.method=='POST':
        cate = request.POST['cate']
        prov = request.POST['province']
        city = request.POST['city']
        dist = request.POST['dist']
        comp_id = request.POST['company']
        group = request.POST['group']
        startTime = request.POST['startTime']
        endTime = request.POST['endTime']
        rtype = request.POST['rtype']
        mtype = request.POST['mtype']
    else:
        cate = 'cate'
        prov = 'province'
        city = 'city'
        dist = 'dist'
        comp_id='company'
        group = 'group'
        startTime = ''
        endTime = ''
        rtype = 'customer'
        mtype = 'all'
    initial={'cate':cate,'province':prov,'city':city,'dist':dist,'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime,'rtype':rtype,'mtype':mtype}
    myForm = ExportMacsForm(initial=initial)
    
    myForm = export_base_feild_form(request,myForm,initial)
    
    if prov=='province':prov = None
    if cate == 'cate':cate= None
    if comp_id=='company':comp_id=None
    if city == 'city':city = None
    if dist == 'dist':dist=None
    if group == 'group':group = None
    
    gdatas = None
    if comp_id!=None or prov!=None or cate!=None:
        gdatas = myFormDatas.get_groups_data(comp_id=comp_id, prov=prov, city=city, dist=dist,cate=cate,shop_group=group)
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and len(gdatas)>0:
        dgroups = []
        while 1:
            if os.path.exists(export_path):break
            commands.getstatusoutput('mkdir -p %s'%export_path)
        export_file = __export_file__name__(export_path=export_path,prefix='macs',suffix='txt',
                                      comp_id=comp_id,cate=cate,group=group,
                                      prov=prov,city=city,dist=dist,
                                      startTime=startTime,endTime=endTime,otype=rtype,mtype=mtype)
        for group_id,group_name in gdatas:
            dgroups.append(group_id)
        myExportMacs.export_macs_by_role(groups=dgroups, startTime=startTime, endTime=endTime, rtype=rtype,mtype=mtype ,export_file=export_path+'/'+export_file)
        #return render_to_response('download/macs/%s/%s'%(day,export_file),context_instance=RequestContext(request))
        response = HttpResponse(FileWrapper(open(export_path+'/'+export_file)), content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename=%s'%urlquote(export_file)
        return response
    return render_to_response('zmExport/export_macs.html',{'form':myForm,'gdatas':gdatas},context_instance=RequestContext(request))



from export_hour_data import myExportLorealData


def export_hour_data_from_mysql(request):
    '''导出小时数据'''
    #print request
    day = datetime.date.today().strftime('%Y-%m-%d')
    export_path = os.path.join(current_dir,'../../templates/download/macs/%s'%day) 
    myForm = ExportHourDataForm()
    if request.method=='POST':
        cate = request.POST['cate']
        prov = request.POST['province']
        city = request.POST['city']
        dist = request.POST['dist']
        comp_id = request.POST['company']
        group = request.POST['group']
        startTime = request.POST['startTime']
        endTime = request.POST['endTime']
        temp = request.POST['temp']
    else:
        cate = myForm.fields['cate'].choices[0][0]
        prov = myForm.fields['province'].choices[0][0]
        city = myForm.fields['city'].choices[0][0]
        dist = myForm.fields['dist'].choices[0][0]
        comp_id=myForm.fields['company'].choices[0][0]
        group = myForm.fields['group'].choices[0][0]
        startTime = ''
        endTime = ''
        temp = myForm.fields['temp'].choices[0][0]

    initial={'cate':cate,'province':prov,'city':city,'dist':dist,'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime,'temp':temp}
    myForm.initial = initial
    myForm = export_base_feild_form(request,myForm,initial)
    
    if prov=='province':prov = None
    if cate == 'cate':cate= None
    if comp_id=='company':comp_id=None
    if city == 'city':city = None
    if dist == 'dist':dist=None
    if group == 'group':group = None
    
    gdatas = None
    if comp_id!=None or prov!=None or cate!=None:
        gdatas = myFormDatas.get_groups_data(comp_id=comp_id, prov=prov, city=city, dist=dist,cate=cate,shop_group=group)
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and len(gdatas)>0:
        dgroups = []
        
#         export_file = __export_file__(export_path=export_path,prefix='hour_datas',
#                                       comp_id=comp_id,cate=cate,group=group,
#                                       prov=prov,city=city,dist=dist,
#                                       startTime=startTime,endTime=endTime,otype=temp)
        for group_id,group_name in gdatas:
            dgroups.append(group_id)
        #myExportMacs.export_macs_by_role(groups=dgroups, startTime=startTime, endTime=endTime, rtype=rtype, export_file=export_path+'/'+export_file)
        
        #return render_to_response('download/macs/%s/%s'%(day,export_file),context_instance=RequestContext(request))
#         response = HttpResponse(FileWrapper(open(export_path+'/'+export_file)), content_type='application/zip')
#         response['Content-Disposition'] = 'attachment; filename=%s'%urlquote(export_file)
#         return response
        
        hourDatas  = myExportLorealData.get_hour_flow_datas( comp_id=comp_id, groups=dgroups, startTime=startTime, endTime=endTime)
        hourFields = hourDatas[0]
    else:
        #hourDatas = [[u'日期',u'星期',u'时间段',u'名称',u'门店',u'品牌',u'店铺编码',u'归属省份',u'归属城市',u'客流量',u'入店量',u'路过客流']]
        #hourDatas = [['日期','星期','时间段','名称','门店','品牌','店铺编码','归属省份','归属城市','客流量','入店量','路过客流']]
        #hourDatas = []
        hourFields = None
        hourDatas = [["日期","星期","时间段","名称","门店","品牌","店铺编码","归属省份","归属城市","客流量","入店量","路过客流"]]
        #print simplejson.dumps(hourDatas)
    title = __export_file__name__(export_path=export_path,prefix='小时数据',suffix='',
                                      comp_id=comp_id,cate=cate,group=group,
                                      prov=prov,city=city,dist=dist,
                                      startTime=startTime,endTime=endTime) 
        
    return render_to_response('zmExport/export_hour_data.html',{'title':title,'form':myForm,'gdatas':gdatas,'hourDatas':simplejson.dumps(hourDatas[1:]),'hourFields':hourFields},context_instance=RequestContext(request))



